package services

import (
	"errors"
	"fmt"

	"github.com/deploy-services/v2/log"

	driver_handle "github.com/deploy-services/v2/driver"
	"github.com/deploy-services/v2/kcfg"
)

type Set map[interface{}]bool

func (s *Set) Size() int {
	return len(*s)
}

func (s *Set) Has(key interface{}) bool {
	_, ok := (*s)[key]
	return ok
}

func (s *Set) Insert(key interface{}) {
	(*s)[key] = true
}

func (s *Set) InsertSet(set Set) {
	for k, _ := range set {
		(*s)[k] = true
	}
}

func (s *Set) Erase(key interface{}) {
	delete(*s, key)
}

func (s *Set) Dump(prefix string) string {
	var ss string
	for k, _ := range *s {
		ss += fmt.Sprintf("%v%v\n", prefix, k)
	}
	return ss
}

func NewSet() Set {
	return make(Set)
}

type cmd_batch struct {
	cmd []string
}

func (c *cmd_batch) run(s *service, n *node, d driver_handle.Handle) error {
	if len(c.cmd) == 0 {
		return nil
	}
	var e error
	for i, str := range c.cmd {
		str = replace_value(s, n, str)
		log.Logger().Debug("CMD %v : %v Start Run", i, str)
		out, err := d.Execute(str)
		log.Logger().Debug("CMD %v : %v Run Result <%v> Err:%v", i, str, out, err)
		if err != nil {
			e = errors.New(str + " Err:" + err.Error())
			break
		}
	}
	return e
}

func (c *cmd_batch) parse(n *kcfg.Node) {
	c.cmd = []string{}
	nodes := n.Childs("cmd")
	for _, nd := range nodes {
		c.cmd = append(c.cmd, nd.GetString())
	}
}
